from time import sleep
from flask import Flask, jsonify, json, request
from flask_socketio import SocketIO, emit
from cancellable_timer import CancellableTimer

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode="gevent")

class Pile:

    job = None

def notify(total, sid, user):
    socketio.emit(
        'Notification',
        {"user" : user, "total_fee": total, "mode": "fast"},
        room=sid
    )


users = {}

pile = Pile()


@socketio.on('get_tab', namespace="/")
def send_tab(obj):
    print("{}: {}".format(request.sid, obj['user']))
    emit(
        'tab_info', 
        { 'table' : ["we", "are", "fools"] },
        room=request.sid
    )
    # schedule callback
    pile.job = CancellableTimer(5, notify, kwargs={"total": 10, "sid": request.sid, "user": obj['user']})
    pile.job.start()

@socketio.on('my_sid', namespace="/")
def send_tab(obj):
    print("{}: {}".format(request.sid, obj['user']))
    emit(
        'your_sid',
        { 'ID' : request.sid },
        room=request.sid
    )

@socketio.on('cancel')
def cancel(obj):
    if pile.job.cancel():
        print("{} successfully cancelled a job".format(obj['user']))
    else:
        print("Job executing, too late")
    

if __name__ == "__main__":
    socketio.run(app, host="localhost", port=1200, use_reloader=False)


